﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Xml;

namespace libUtilities
{
    public class OtherUtils
    {
        public static String GetServerIP(String IPVersion)
        {
            String ip = "";
            try
            {
                String hostName = Dns.GetHostName();
                IPHostEntry ipEntry = Dns.GetHostEntry(hostName);

                IPAddress[] address = ipEntry.AddressList;
                for (int i = 0; i < address.Length; i++)
                {
                    if (IPVersion.Contains("4")) //IPv4
                    {
                        if (address[i].AddressFamily == AddressFamily.InterNetwork)
                        {
                            ip = address[i].ToString();
                        }
                    }
                    else if (IPVersion.Contains("6")) //IPv6
                    {
                        if (address[i].AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            ip = address[i].ToString();
                        }
                    }
                }
                //No network connection
                if ("::1".Equals(ip) || "127.0.0.1".Equals(ip))
                    ip = "-1";
            }
            catch (SocketException ex)
            {
                throw ex;
            }
            return ip;
        }

        public static int GetANewPort()
        {
            Random rd = new Random(System.DateTime.Now.Millisecond);
            double rdf = rd.NextDouble();
            int rdPort = 2000 + (int)((60000 - 2000) * ((float)rdf));
            return rdPort;
        }

        public static void InitServer(ref String ip, ref int port)
        {
            //Get server IP Address
            ip = GetServerIP("ipv4");

            //Get server Port
            port = GetANewPort();
        }

        public static String getPath()
        {
            String curPath = Directory.GetCurrentDirectory();
            return curPath;
        }

        public static void WriteFile(String path, String info)
        {
            try
            {
                if (!File.Exists(path))
                {
                    File.Create(path);
                }
                StreamWriter sw = new StreamWriter(path);
                sw.Write(info);
                sw.Close();
            }
            catch (IOException ex)
            {
                throw ex;
            }
        }

        public static bool IsPositiveNumber(String num)
        {
            try
            {
                if (num == "" || num == null)
                    return false;
                for (int i = 0; i < num.Length; i++)
                    if (num[i] < '0' || num[i] > '9')
                        return false;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string GenerateTemporaryKey()
        {
            //TO DO: Create a random key for communicating between server and client 

            return "asdfghjkl";
        }

        #region XML Helper
        public static bool isFileExist(String name)
        {
            bool exist = File.Exists(name);
            if (exist)
                return true;
            return false;
        }

        private static void loadXml(String name, XmlDocument doc)
        {
            try
            {
                bool exist = isFileExist(name);
                if (!exist)
                {
                    FileStream f = File.Create(name);

                    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
                    doc.AppendChild(dec);
                    XmlNode root = doc.CreateNode(XmlNodeType.Element, "root", null);
                    doc.AppendChild(root);
                    doc.Save(f);

                    f.Close();
                }
                else
                    doc.Load(name);
            }
            catch (XmlException ex)
            {
                throw ex;
            }
        }

        public static XmlDocument initXml(String directory, String fileName)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                bool directoryExist = Directory.Exists(directory);
                if (!directoryExist)
                {
                    Directory.CreateDirectory(directory);
                }
                loadXml(directory + @"/" + fileName, doc);
                return doc;
            }
            catch (XmlException ex)
            {
                throw ex;
            }
        }

        private static void loadXml(String name, XmlDocument doc, bool isOverwritten)
        {
            try
            {
                bool exist = isFileExist(name);
                if (!exist || (exist && isOverwritten))
                {
                    FileStream f = File.Create(name);

                    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
                    doc.AppendChild(dec);
                    XmlNode root = doc.CreateNode(XmlNodeType.Element, "root", null);
                    doc.AppendChild(root);
                    doc.Save(f);

                    f.Close();
                }
                else
                    doc.Load(name);
            }
            catch (XmlException ex)
            {
                throw ex;
            }
        }

        public static XmlDocument initXml(String directory, String fileName, bool isOverwritten)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                bool directoryExist = Directory.Exists(directory);
                if (!directoryExist)
                {
                    Directory.CreateDirectory(directory);
                }
                loadXml(directory + @"/" + fileName, doc, isOverwritten);
                return doc;
            }
            catch (XmlException ex)
            {
                throw ex;
            }
        }
        #endregion

    }
}
